# -*- coding:utf-8 -*-

import json

from flask import Blueprint, request
import requests

from apps import exception, result
from apps.views import api_decorator

bp = Blueprint('search', __name__, url_prefix='/search')

subscription_key = 'a1cd974810ee4f3aa6ed69ba2aa009b9'
assert subscription_key

bingSearch = 'https://api.cognitive.microsoft.com/bing/v7.0/search'


@bp.route('', methods=['POST'])
@api_decorator
def bing():
    content = request.json or {}
    search_term = content.get('search_term', None)
    if not search_term:
        raise exception.ParameterException('search_term', search_term)

    headers = {"Ocp-Apim-Subscription-Key": subscription_key}
    params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
    response = requests.get(bingSearch, headers=headers, params=params)
    response.raise_for_status()
    json_data = response.json()
    json_data = json.dumps(json_data).replace('<b>', '<').replace('</b>', '>')
    json_data = json.loads(json_data)
    return result.from_data(json_data)